package com.briup.ch12;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/20
 * @Description:
 */
public class TCPClient {
    public static void main(String[] args) {
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        Scanner scanner = new Scanner(System.in);
        ArrayList<Teacher> teachers = new ArrayList<>();

        try {
            // 连接服务器（IP为本地，端口8002）
            socket = new Socket("localhost", 8002);
            // 输出流：向服务器发送对象
            oos = new ObjectOutputStream(socket.getOutputStream());

            System.out.println("请输入老师信息（格式：姓名-年龄-工资，输入quit结束）：");
            while (true) {
                String input = scanner.nextLine();
                if ("quit".equals(input)) {
                    break;
                }
                // 拆分输入的字符串
                String[] parts = input.split("-");
                String name = parts[0];
                int age = Integer.parseInt(parts[1]);
                double salary = Double.parseDouble(parts[2]);
                // 封装为Teacher对象并加入集合
                teachers.add(new Teacher(name, age, salary));
            }

            // 发送老师对象集合给服务器
            oos.writeObject(teachers);
            oos.flush();

            // 输入流：接收服务器的响应
            ois = new ObjectInputStream(socket.getInputStream());
            String response = (String) ois.readObject();
            System.out.println("服务器响应：" + response);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (ois != null) ois.close();
                if (oos != null) oos.close();
                if (socket != null) socket.close();
                scanner.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}